package com.screw.carnival.sdk.bridge;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.screw.carnival.sdk.SCarnivalBusiness;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;

public class SCarnivalCocosBridge implements SCarnivalCocosIAP {

    private static SCarnivalCocosBridge callbackApi;
    public static WeakReference<Activity> mainGameActivity;
    private Method evalString;
    private Method runOnGLThread;
    private static Handler handler = new Handler(Looper.getMainLooper());

    public static SCarnivalCocosBridge getInstance() {
        if (callbackApi == null) {
            callbackApi = new SCarnivalCocosBridge();
        }
        return callbackApi;
    }

    public void setMainGameActivity(Activity activity) {
        mainGameActivity = new WeakReference<>(activity);

    }

    @Override
    public void XSSdkCallback(String action, String jsonData) {
        if (mainGameActivity != null && mainGameActivity.get() != null) {

            handler.post(() -> {

                check();

                try {
                    runOnGLThread.invoke(mainGameActivity.get(), (Runnable) () -> {
                        try {
                            evalString.invoke(null, String.format("window.VideoCallback('%s','%s')", action, jsonData));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private void check() {
        if (runOnGLThread==null){
            initRunOnGLThread();
        }
        if (evalString == null){
            initEvalString();
        }
    }


    private void initEvalString() {
        try {
            String cocos2dxJavascriptJavaBridgePath = "org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge";
            Class clzBridge = Class.forName(cocos2dxJavascriptJavaBridgePath, false, SCarnivalBusiness.context.getClassLoader());
            evalString = clzBridge.getDeclaredMethod("evalString", String.class);
            evalString.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initRunOnGLThread() {
        try {
            String cocos2dxActivityPath = "org.cocos2dx.lib.Cocos2dxActivity";
            Class clzCocos2dAct = Class.forName(cocos2dxActivityPath, false, SCarnivalBusiness.context.getClassLoader());
            runOnGLThread = clzCocos2dAct.getDeclaredMethod("runOnGLThread", Runnable.class);
            runOnGLThread.setAccessible(true);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
